package com.example.shiro.demo.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.shiro.demo.dao.UserRepository;
import com.example.shiro.demo.entity.User;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <Description> Form 拦截器<br>
 *
 * @author renweiping<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2019/10/15 13:21 <br>
 * @see com.example.shiro.demo.shiro <br>
 */

public class ExtendFormAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(ExtendFormAuthenticationFilter.class);

    private UserRepository userRepository;

    public ExtendFormAuthenticationFilter(UserRepository userRepository){
        this.userRepository = userRepository;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }

                return this.executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                return true;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the Authentication url [" + this.getLoginUrl() + "]");
            }
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg", "未登录，无法访问该地址");
            out.println(jsonObject.toJSONString());
            out.flush();
            out.close();
            return false;
        }
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        HttpSession session = ((HttpServletRequest) request).getSession();
        User user = userRepository.findByName(token.getPrincipal().toString());
        session.setAttribute("user", user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "登录成功");

        out.println(jsonObject.toJSONString());
        out.flush();
        out.close();
        return true;

    }


}
